package com.example.llm.learn.reactiveweb.emplyee.controller;

import com.example.llm.learn.reactiveweb.emplyee.dto.EmployeeDTO;
import com.example.llm.learn.reactiveweb.emplyee.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping(value = "/employee/getById")
    public Mono<EmployeeDTO> getById(Integer id) {
        return employeeService.getById(id)
                .delayElement(Duration.ofMillis(6000))
                .doOnNext(employeeDTO -> log.info("getById server produce => {}", employeeDTO));
    }

    //    @GetMapping(value = "/employee/getList", produces = "application/stream+json;charset=UTF-8") // 该格式已经被弃用
//    @GetMapping(value = "/employee/getList", produces = "application/x-ndjson;charset=UTF-8") // 也可以以流式返回
    @GetMapping(value = "/employee/getList", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @CrossOrigin(origins = "null")
    public Flux<EmployeeDTO> getList() {
        return employeeService.getList()
//                .delayElements(Duration.ofMillis(1000))
                .doOnNext(employeeDTO -> log.info("getList server produce => {}", employeeDTO));
    }

    @GetMapping(path = "/testSSE", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamSse() {
        // 每500毫秒生成一个序号
        return Flux.interval(Duration.ofMillis(500))
                .map(seq -> seq.toString())
                // 调试用：打印到控制台
                .doOnNext(log::info);
    }

}